<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 临时用餐申请编辑 -->

    <a-spin :spinning="loading.SUBMITTED || loading.DRAFT || loading.REJECTED || loading.PAST">
      <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
        :rules="editModel != 0 ? rules : {}">
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />
          <custom-form ref="customForm" :form-list="formList" :form="form" :edit-model="editModel == 0 ? '' : ''"
            @getOption="getOption" @change="changeDate" />
          <a-row :gutter="24">
            <a-col v-if="editModel != 0" :md="24" :sm="24">
              <a-form-model-item label="附件" prop="fileInfos">
                <l-table count="5" business-code="OF05" :upload-arrys.sync="form.fileInfos" />
              </a-form-model-item>
            </a-col>
            <a-col v-else :md="24" :sm="24">
              <a-form-model-item label="附件" prop="fileInfos">
                <file-link :file-list="form.fileInfos" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- </a-form-model> -->
        </a-card>

        <a-card v-if="form.mealsType == '605004528177254566'" :bordered="false">
          <!-- 临时用餐人员信息 -->
          <title-name title="临时用餐人员信息" />
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <div class="flex-row mb20">
                <a-button :disabled="editModel == 0" class="ml20" type="primary" @click="addLine()">
                  添加行
                </a-button>
              </div>
              <s-table ref="table" class="mb20" bordered size="default" row-key="key" :columns="columns"
                :data="loadData" :is-delete="true" :alert="true" show-size-changer show-quick-jumper
                :show-pagination="false">
                <template slot="name" slot-scope="text, record">
                  <BaseInput v-model="record.name" :disabled="!record.editable" placeholder="请输入" />
                </template>
                <template slot="orgName" slot-scope="text, record">
                  <BaseInput v-model="record.orgName" :disabled="!record.editable" placeholder="请输入" />
                </template>

                <template slot="action" slot-scope="text, record, index">
                  <span v-if="record.editable">
                    <a @click="() => save(record)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要取消保存?" @confirm="() => cancel(record.key, index)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a :disabled="editingKey !== '' || editModel == 0" @click="() => edit(record.key)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                      <a :disabled="editingKey !== '' || editModel == 0">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </s-table>
            </a-col>

            <a-col :md="8" :sm="8">
              <a-form-model-item label="用餐人数">
                <BaseInput v-model="form.mealsNum" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="费用合计(元)">
                <BaseInput v-model="form.mealsCost" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card v-if="form.officeCanteenReceptionMeal">
          <title-name title="临时用餐人员信息" />
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="接待餐费用">
                <BaseInput v-model="form.officeCanteenReceptionMeal.mealMoney" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="填写人">
                <BaseInput v-model="form.officeCanteenReceptionMeal.creatorName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="填写时间">
                <BaseInput v-model="form.officeCanteenReceptionMeal.createTime" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <a-form-model-item label="*附件">
                <file-link :file-list="form.officeCanteenReceptionMeal.fileInfoVOS" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div v-if="editModel != 0" class="tool-btns mb20 page-btn-right-top">
      <a-button v-if="form.auditStatus == 'REJECTED' || form.auditStatus == 'PAST'"
        :loading="loading.REJECTED || loading.PAST" :disabled="loading.SUBMITTED || loading.DRAFT" type="primary"
        class="button_right" @click="handleSubmit(form.auditStatus)">
        保存
      </a-button>

      <a-button v-else :loading="loading.DRAFT" :disabled="loading.SUBMITTED || loading.REJECTED" type="primary"
        class="button_right" @click="handleSubmit('DRAFT')">
        保存草稿
      </a-button>

      <a-button v-if="form.auditStatus != 'PAST'" :loading="loading.SUBMITTED"
        :disabled="loading.REJECTED || loading.DRAFT || loading.PAST" type="primary" class="button_right ml20"
        @click="handleSubmit('SUBMITTED')">
        提交
      </a-button>
      <a-button class="ml20" type="primary" @click="handleClose"> 关闭 </a-button>
    </div>
    <div v-else class="tool-btns mb20 page-btn-right-top">
      <a-button class="ml20" type="primary" v-if="checkVisibleInDetail" @click="handleClose"> 关闭 </a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import { getCasualMealsApply, addCasualMealsApply, updateCasualMealsApply } from '@/api/office/canteen' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import Selector from '@/components/Select/Selector'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import SelectOrgDepartment from '@/components/Select/SelectOrgDepartment'
import { STable } from '@/components' // 表格
import UploadList from '@/components/UploadList'
import { useStandFee } from '../hooks.js'
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
    width: '30%'
  },
  {
    title: '归属单位',
    dataIndex: 'orgName',
    scopedSlots: { customRender: 'orgName' },
    width: '30%'
  },
  //     {
  //     title: '归属单位',
  //     dataIndex: 'phone',
  //     scopedSlots: { customRender: 'phone' },
  //     width: '30%',
  // },

  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    STable
  },
  extends: new BaseEditPage(),
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  data() {
    const lessorTel = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatorMealsNum = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/
      if (value < 1) {
        callback(new Error('用餐人数不得小于0人'))
      } else {
        callback()
      }
    }
    this.columns = columns
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      loading: { DRAFT: false, REJECTED: false, SUBMITTED: false, PAST: false }, // 草稿和提交按钮loding
      form: {
        orgIdStr: '',
        orgId: '',
        makeUserId: '',
        mealsType: '605004528177254566',
        makeDeptId: '',
        makeUserPhone: '',
        personList: [],
        mealsNum: 0,
        mealsCost: 0,
        isPublicDept: 0,
        mealsTimeList: []
      }, // 表单
      rules: {
        mealsType: [{ required: true, message: '请选择用餐类别', trigger: 'change' }],
        isPublicDept: [{ required: true, message: '请选择是否公共部门', trigger: 'change' }],
        makeDeptId: [{ required: true, message: '请选择预约部门', trigger: 'change' }],
        makeUserId: [{ required: true, message: '请选择预约人', trigger: 'change' }],
        makeUserPhone: [{ required: true, validator: lessorTel, trigger: 'change' }],
        mealsDate: [{ required: true, message: '请选择用餐时间 ', trigger: 'change' }],
        mealsTimeList: [{ required: true, message: '请选择用餐时段 ', trigger: 'change' }],
        mealsNum: [{ required: true, validator: validatorMealsNum, trigger: 'change' }],
        receptionLevel: [{ required: true, message: '请输入接待级别 ', trigger: 'change' }],
        matter: [{ required: true, message: '请输入事由 ', trigger: 'change' }],
        // fileInfos: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }]
      }, // 校验规则
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.personList
          })
        })
      },

      rulesFile: {},
      init: false, // 初始化控件
      key: 0,
      cacheData: {},
      editingKey: '',
      status: false //第一次不请求
    }
  },
  watch: {
    // 监听附件实现附件校验
    // 'form.fileInfos'() {
    //   if (this.editModel != 0 && this.init) {
    //     this.$nextTick(() => {
    //       this.$refs.ruleForm?.validateField('fileInfos')
    //     })
    //   }
    // },
    'form.makeUserPhone'() {
      if (arguments[0] == arguments[1]) {
        return
      }
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('makeUserPhone')
        })
      }
    },
    'form.mealsTimeList'() {
      if (arguments[0]?.toString() == arguments[1]?.toString()) {
        return
      }
      if (this.form.mealsType == '605004528177254566') {
        this.calculate()
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = '0'
          })
        }
      }
    }
  },
  mounted() {
    if (this.editModel == -1) {
      this.$route.meta.title = '临时用餐台账查看'
      this.editModel = 0
    } else {
      this.$route.meta.title = ['临时用餐申请查看', '临时用餐申请编辑', '临时用餐申请新增'][this.editModel]
    }

    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading.DRAFT = true
      this.loading.REJECTED = true
      this.loading.SUBMITTED = true
      getCasualMealsApply(this.id)
        .then(res => {
          this.loading.DRAFT = false
          this.loading.REJECTED = false
          this.loading.SUBMITTED = false
          res.data.mealsDate = []
          res.data.mealsDate[0] = res.data.mealsDateStart
          res.data.mealsDate[1] = res.data.mealsDateEnd
          res.data.personList = res.data.personList || []
          this.form = { ...res.data }
          this.$nextTick(() => {
            this.init = true
            this.form.makeUserId = res.data.makeUserId
          })
          this.$refs.table.refresh(true)
        })
        .catch(() => {
          this.loading.DRAFT = false
          this.loading.REJECTED = false
          this.loading.SUBMITTED = false
        })
    } else {
      let userInfo = this.$userInfo()

      this.form.orgIdStr =
        (userInfo.currentPost.code === 'PD' ? userInfo.currentPost.orgName + '-' : '') + userInfo.currentPost.name
      this.form.orgId = userInfo.currentPost.code === 'PD' ? userInfo.currentPost.id : userInfo.currentPost.orgId
      this.form.makeUserId = userInfo.id
      this.form.makeDeptId = userInfo.currentPost.deptId
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'orgIdStr',
          type: 'BaseInput',
          label: '单位',
          disabled: true
        },
        {
          keyName: 'mealsType',
          disabled: this.editModel == 0,
          label: '用餐类别',
          type: Selector,
          attrs: {
            selectType: '16',
            urlType: 'union'
          }
        },
        {
          keyName: 'isPublicDept',
          type: 'a-select',
          hidden: this.form.mealsType == '605004528177254566',
          disabled: this.editModel == 0,
          label: '是否公共部门',
          data: [
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          type: SelectOrgDepartment,
          keyName: 'makeDeptId',
          label: '预约部门',
          disabled: this.editModel == 0,
          hidden: this.form.isPublicDept == 1,
          attrs: {
            orgId: this.form.orgId,
            autoSelected: false
            // isAutoSelectMe: this.editModel == 2,
          }
        },
        {
          type: SelectPersonByProject,
          keyName: 'makeUserId',
          disabled: this.editModel == 0,
          label: '预约人',
          attrs: {
            orgId: { 1: this.form.orgId, 0: this.form.makeDeptId }[this.form.isPublicDept],
            isOrg: true,
            showSearch: true,
            addJob: true
          }
        },
        {
          keyName: 'makeUserPhone',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '预约人电话'
        },
        {
          keyName: 'mealsDate',
          type: 'a-range-picker',
          disabled: this.editModel == 0,
          placeholder: ['请选择日期', '请选择日期'],
          label: '用餐时间',

          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: current => {
              let date = new Date()
              let date1 = new Date(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' 14:00')
              console.log(this.moment(current))
              if (date > date1) {
                return current && current < this.moment().startOf('day' + 1)
              } else {
                return current && current < this.moment().startOf('day')
              }
            }
          }
        },
        {
          keyName: 'mealsTimeList',
          disabled: this.editModel == 0,
          label: '用餐时段',
          type: 'a-select',
          attrs: {
            mode: 'multiple'
          },
          data: [
            {
              label: '早餐',
              value: '1'
            },
            {
              label: '午餐',
              value: '2'
            },
            {
              label: '晚餐',
              value: '3'
            }
          ]
        },
        {
          keyName: 'matter',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '事由'
        },
        {
          keyName: 'mealsNum',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          hidden: this.form.mealsType != '605004528177254567',
          label: '用餐人数'
        },
        {
          keyName: 'receptionLevel',
          disabled: this.editModel == 0,
          label: '接待级别',
          hidden: this.form.mealsType != '605004528177254567',
          type: Selector,
          attrs: {
            selectType: '17',
            urlType: 'union'
          }
        },
        {
          keyName: 'remarks',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '备注',
          span: 24
        }
      ]
    }
  },

  methods: {
    getOption(name, e) {
      if (name == 'makeDeptId') {
        this.form.makeDeptName = e.name
      }
      if (name == 'makeUserId') {
        this.form.makeUserName = e.name
        this.form.makeUserPhone = e.phone
      }

      if (name == 'mealsType' && this.form.mealsType == '605004528177254567') {
        this.form.personList = []

        this.key = 0
        this.calculate()
      } else if (name == 'mealsType' && this.form.mealsType == '605004528177254566') {
        this.form.mealsNum = this.form.personList?.length
      }
    },
    changeDate(name, e) {
      if (name == 'mealsDate' && this.form.mealsType == '605004528177254566') {
        this.calculate()
      }
    },
    addLine() {
      this.form.personList.push({
        key: this.key,
        name: '',
        orgName: '',

        isSave: false,
        editable: true
      })
      this.key++
      this.cacheData = this.form.personList.map(item => ({ ...item }))
      this.$refs.table.refresh(true)
    },
    cancel(key, index) {
      const newData = [...this.form.personList]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = ''
      if (target.isSave) {
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
          delete target.editable
          this.form.personList = newData
        }
      } else {
        this.form.personList.splice(index, 1)
      }

      this.$refs.table.refresh(true)
    },
    save(data) {
      data.isSave = true
      data.editable = false
      this.editingKey = ''
      this.calculate()
      this.$refs.table.refresh(true)
    },
    edit(key) {
      const newData = [...this.form.personList]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.form.personList = newData
      }
      this.cacheData = this.form.personList.map(item => ({ ...item }))
      this.$refs.table.refresh(true)
    },
    del(data, idx) {
      this.form.personList.splice(idx, 1)
      this.calculate()
      this.$refs.table.refresh(true)
    },
    calculate() {
      // if (this.form.mealsType == '605004528177254566') {
      //     console.log(this.form.mealsNum)
      //     this.form.mealsNum = this.form.personList?.length
      // }
      if (this.status) {
        const standFee = useStandFee()
        this.form.mealsCost = 0
        this.form.mealsTimeList?.forEach(i => {
          if (i == 1) {
            this.form.mealsCost += this.form.personList.length * standFee[0] * this.datedifference()
          } else if (i == 2) {
            this.form.mealsCost += this.form.personList.length * standFee[1] * this.datedifference()
          } else {
            this.form.mealsCost += this.form.personList.length * standFee[2] * this.datedifference()
          }
        })
      } else {
        this.status = true
      }
    },
    //两个时间相差天数 兼容firefox chrome
    datedifference() {
      //sDate1和sDate2是2006-12-18格式
      if (this.form.mealsDate) {
        let sDate1, sDate2, dateSpan
        sDate1 = Date.parse(this.form.mealsDate[0])
        sDate2 = Date.parse(this.form.mealsDate[1])
        dateSpan = sDate2 - sDate1
        dateSpan = Math.abs(dateSpan)
        return Math.floor(dateSpan / (24 * 3600 * 1000)) + 1
      } else {
        return 0
      }
    },

    /**
     * 提交表单
     */
    handleSubmit(auditStatus) {
      let that = this
      let api = [updateCasualMealsApply, addCasualMealsApply][that.editModel - 1] // 根据操作切换url地址

      // 校验表单
      that.$refs.ruleForm.validate(e => {
        if (e) {
          // 提交表单
          if (this.form.personList.length == 0 && this.form.mealsType == '605004528177254566') {
            that.$message.warning('请填写用餐人员')
            return
          }
          if (that.form.mealsDate[0].split('-')[1] != that.form.mealsDate[1].split('-')[1]) {
            that.$message.warning('用餐时间的开始结束时间必须在一个月内')
            return
          }
          that.loading[auditStatus] = true
          that.form.auditStatus = auditStatus
          that.form.mealsDateStart = that.form.mealsDate[0]
          that.form.mealsDateEnd = that.form.mealsDate[1]
          let form = that.$clone(that.form)
          api(form)
            .then(() => {
              that.loading[auditStatus] = false
              if (auditStatus == 'SUBMITTED') {
                that.$message.success('提交成功！')
              } else {
                that.$message.success('保存成功！')
              }
              that.$multiTab.close()
            })
            .catch(() => {
              that.loading[auditStatus] = false
            })
        }
      })
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>
